package com.hdl.filter;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * CommentFilter 敏感词汇过滤器
 */
@WebFilter("/commentAdd.let")//拦截评论
public class CommentFilter implements Filter {

	 //敏感词汇集合
    private List<String> list = new ArrayList<>();

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //代理模式

        //获取代理对象
        ServletRequest request = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                //判断是否是需要增强的方法
                if(method.getName().equals("getParameter")){//是

                    //执行方法获取返回值
                    String value = (String) method.invoke(req, args);
                    for (String msg : list) {
                        if(value.contains(msg)){
                            value = value.replaceAll(msg,"***");
                        }
                    }
                    return value;
                }
                return method.invoke(req,args);
            }
        });

        chain.doFilter(request, resp);
    }

    public void init(FilterConfig config) throws ServletException {

        //加载敏感词文件
        ServletContext servletContext = config.getServletContext();

        //获取真实路径
        String realPath = servletContext.getRealPath("/WEB-INF/classes/sensitive.txt");

        try {
            //创建字符流读取文件
            BufferedReader br = new BufferedReader(new FileReader(realPath));
            String line = null;
            while ((line = br.readLine()) != null){//读取
                //存储敏感词汇
                list.add(line);
            }

            //释放资源
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
	

}
